#include <stdlib.h>
#include <stdio.h>
#include "symboles.h"




struct variable*
ajouter_var(struct variable** t,struct type* ty,char* id){
 struct variable* new = malloc(sizeof(struct variable));
 if(new==NULL)
   exit(EXIT_FAILURE);
 new->nom_var=id;
 new->numvar=cmpt_val;
 cmpt_val++;
 new->tvar=ty;
 new->suivant=*t;
 *t=new;
 return *t;
}

void
ajouter_arg(struct variable* f,char* id,enum nom_type ty){
 struct arg* new = malloc(sizeof(struct arg));
 if(new==NULL)
   exit(EXIT_FAILURE);
 new->nom_arg=id;
 new->ty_arg=ty;
 new->suivant=f->tvar->fct_params->arg1;
 f->tvar->fct_params->arg1=new;
}

void
ajouter_fct(struct variable* classe,char* f){
 struct fct* new = malloc(sizeof(struct fct));
 if(new==NULL)
   exit(EXIT_FAILURE);
 new->nom_fct=f;
 new->suivant=classe->tvar->class_fcts;
 classe->tvar->class_fcts=new;
}

enum nom_type
type(struct variable* t,char* id){
  if(t==NULL)
    return UNDEF;
  else if(t->nom_var==id)
    return t->tvar->ntype;
  else return type(t->suivant,id);
}

void
liberer_table(struct variable* t){
  liberer_type(t->tvar);
  liberer_table(t->suivant);
  free(t);
}

void
liberer_type(struct type* ty){
  if(ty->class_fcts!=NULL){
    liberer_fct(ty->class_fcts);
  }
  if(ty->fct_params!=NULL){
    if(ty->fct_params->arg1!=NULL)
      liberer_arg(ty->fct_params->arg1);
    free(ty->fct_params);
  }
  free(ty);
}

void
liberer_fct(struct fct* f){
  if(f->suivant!=NULL)
    liberer_fct(f->suivant);
  free(f);
}

void
liberer_arg(struct arg* a){
  if(a->suivant!=NULL)
    liberer_arg(a->suivant);
  free(a);
}
/*
int main(void){
  
  struct variable* t=NULL;
  printf("%d\n",type(t,"a"));//6 attendu

  struct type ty;
  ty.ntype=I;
  ty.vali=3;
  ty.class_fcts=NULL;
  ty.fct_params=NULL;
  ajouter_var(&t,"a",&ty);
  printf("%d\n",type(t,"a"));//2 attendu

  struct arg a={"arg1",I,NULL};
  struct params f={&a,BOOL};
  struct type ty12;
  ty12.ntype=FCT;
  ty12.valst=NULL;
  ty12.class_fcts=NULL;
  ty12.fct_params=&f;
  ajouter_var(&t,"12",&ty12);
  printf("%d\n",type(t,"12"));//4 attendu

  struct fct c={"f",NULL};
  struct type taz;
  taz.ntype=CLAS;
  taz.valst=NULL;
  taz.class_fcts=&c;
  taz.fct_params=NULL;
  ajouter_var(&t,"az",&taz);
  printf("%d\n",type(t,"az"));//5 attendu

  liberer_table(t);

  return EXIT_SUCCESS;
}
*/
//en sortie de fct supprimer var locale de table?->non renommer var avec var_f?

//compteur global ppour donner à chaque var un num unique?
//idee renommer fct ss forme f_c_int_int

//prévoir la libération de t?
